package com.benjamin.sinamicroblogclient;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserFactory;

import android.content.Context;
import android.util.Log;

import com.benjamin.common.WebUtils;

public class MicroblogUtils {

	public List<Status> getStatusList(Context ctx) throws Exception {

		List<Status> statusList = new ArrayList<Status>();
		InputStream stream = null;

		try {

			try {
				Status status = null;
				Status retweeted_status = null;
				User user = null;
				boolean isRetweeted = false;

				String userTimelineURL = ctx
						.getString(R.string.userTimelineXMLURL);

				URL url = new URL(userTimelineURL);
				stream = url.openStream();

				XmlPullParserFactory xmlPullParserFactory = XmlPullParserFactory
						.newInstance();
				XmlPullParser parser = xmlPullParserFactory.newPullParser();

				parser.setInput(stream, null);

				int eventType = parser.getEventType();

				while (eventType != XmlPullParser.END_DOCUMENT) {
					switch (eventType) {
					case XmlPullParser.START_TAG:
						if (parser.getName().equalsIgnoreCase("status")) {
							status = new Status();
							retweeted_status = new Status();
						} else if (parser.getName().equalsIgnoreCase(
								"created_at")) {
							SimpleDateFormat dateFormat = new SimpleDateFormat(
									"EEE MMM dd HH:mm:ss Z yyyy");
							Date date = dateFormat.parse(parser.nextText()
									.trim());

							if (isRetweeted == true) {
								retweeted_status.setCreatedAt(date);
							} else {
								status.setCreatedAt(date);
							}
						} else if (parser.getName().equalsIgnoreCase("text")) {
							String text = parser.nextText().trim();
							if (isRetweeted) {
								retweeted_status.setText(text);
							} else {
								status.setText(text);
							}
						} else if (parser.getName().equalsIgnoreCase("user")) {
							user = new User();
							if (isRetweeted) {
								retweeted_status.setUser(user);
							} else {
								status.setUser(user);
							}
						} else if (parser.getName().equalsIgnoreCase(
								"screen_name")) {
							String screen_name = parser.nextText().trim();
							if (isRetweeted) {
								retweeted_status.getUser().setScreenName(
										screen_name);
							} else {
								user.setScreenName(screen_name);
							}
						} else if (parser.getName().equalsIgnoreCase(
								"profile_image_url")) {
							if (!isRetweeted) {
								user.setProfileImageURL(parser.nextText()
										.trim());
							}
						} else if (parser.getName().equalsIgnoreCase(
								"retweeted_status")) {
							isRetweeted = true;
							retweeted_status = new Status();
							status.setRetweetedStatus(retweeted_status);
						}
						break;
					case XmlPullParser.END_TAG:
						if (parser.getName().equalsIgnoreCase(
								"retweeted_status")) {
							isRetweeted = false;
						} else if (parser.getName().equalsIgnoreCase("status")) {
							statusList.add(status);
						}
						break;

					default:
						break;
					}

					eventType = parser.next();
				}
			} finally {
				if (stream != null) {
					stream.close();
				}
			}
		} catch (Exception ex) {
			Log.e("MicroblogUtils", ex.getMessage(), ex);
			ex.printStackTrace();
			throw ex;
		}

		return statusList;
	}

	private void parseJSONUser(Status status, JSONObject jsonStatus)
			throws JSONException {
		String strText = jsonStatus.getString("text");
		status.setText(strText);

		User user = new User();
		status.setUser(user);

		JSONObject jsonUser = jsonStatus.getJSONObject("user");
		String screen_name = jsonUser.getString("screen_name");
		user.setScreenName(screen_name);
		String profile_image_url = jsonUser.getString("profile_image_url");
		user.setProfileImageURL(profile_image_url);
	}

	public List<Status> getStatusListUsingJSON(Context ctx) throws IOException,
			JSONException {
		List<Status> statusList = new ArrayList<Status>();

		String strJSON = WebUtils.getString(ctx,
				ctx.getString(R.string.userTimelineJSONURL));

		JSONArray jsonArray = new JSONArray(strJSON);
		for (int i = 0; i < jsonArray.length(); i++) {
			JSONObject jsonStatus = jsonArray.getJSONObject(i);
			Status status = new Status();

			String created_at = jsonStatus.getString("created_at");
			status.setCreatedAt(new Date(created_at));

			parseJSONUser(status, jsonStatus);

			// check to see if there is any retweeted_status
			JSONObject jsonRetweetedStatus = jsonStatus
					.optJSONObject("retweeted_status");
			if (jsonRetweetedStatus != null) {
				Status retweetedStatus = new Status();
				status.setRetweetedStatus(retweetedStatus);

				parseJSONUser(retweetedStatus, jsonRetweetedStatus);
			}

			statusList.add(status);
		}

		return statusList;
	}
}
